package com.sjyl.kaoshitong.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.sjyl.kaoshitong.MainActivity;
import com.sjyl.kaoshitong.R;
import com.sjyl.kaoshitong.beans.ApiResponse;
import com.sjyl.kaoshitong.beans.Recontent;
import com.sjyl.kaoshitong.beans.UserInfo;
import com.sjyl.kaoshitong.util.APIUtils;
import com.sjyl.kaoshitong.util.MD5Helper;
import com.sjyl.kaoshitong.util.NetworkHelper;
import com.sjyl.kaoshitong.util.OKHttpUtil;
import com.sjyl.kaoshitong.util.PreferencesKeyUtil;
import com.sjyl.kaoshitong.util.ToastUtil;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by ChangerLow on 15/7/16.
 * Email: changerlow@qq.com
 */
public class LoginFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "LoginFragment";
    private EditText usernameTV;
    private EditText passwdTV;
    private ImageButton usernameClearBtn;
    private ImageButton passwdClearBtn;
    private String username;
    private String passwd;
    private Button submitBtn;

    private TextView registerBtn;
    private TextView forgetPasswdBtn;
    private ProgressDialog dialog;
    private OkHttpClient okHttpClient;
    private Gson gson = new Gson();

    public static LoginFragment newInstance() {
        LoginFragment fragment = new LoginFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Hawk.init(getActivity());
        username = Hawk.get(PreferencesKeyUtil.KEY_USER_NAME, "13559640926");
        passwd = Hawk.get(PreferencesKeyUtil.KEY_PASSWD, "123456");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login_layout, container, false);
        usernameTV = (EditText) view.findViewById(R.id.login_username);
        usernameTV.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0)
                    usernameClearBtn.setVisibility(View.VISIBLE);
                else
                    usernameClearBtn.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        passwdTV = (EditText) view.findViewById(R.id.login_passwd);
        passwdTV.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0)
                    passwdClearBtn.setVisibility(View.VISIBLE);
                else
                    passwdClearBtn.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        usernameClearBtn = (ImageButton) view.findViewById(R.id.username_clear_btn);
        passwdClearBtn = (ImageButton) view.findViewById(R.id.passwd_clear_btn);
        usernameClearBtn.setOnClickListener(this);
        passwdClearBtn.setOnClickListener(this);


        submitBtn = (Button) view.findViewById(R.id.submit_btn);
        submitBtn.setOnClickListener(this);

        registerBtn = (TextView) view.findViewById(R.id.register_btn);
        registerBtn.setOnClickListener(this);

        forgetPasswdBtn = (TextView) view.findViewById(R.id.forget_passwd_btn);
        forgetPasswdBtn.setOnClickListener(this);

        usernameTV.setText(username);
        passwdTV.setText(passwd);

        dialog = new ProgressDialog(getActivity());
        dialog.setIndeterminate(true);
        dialog.setMessage(getResources().getString(R.string.logining));

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.username_clear_btn:
                usernameTV.setText("");
                usernameTV.requestFocus();
                break;
            case R.id.passwd_clear_btn:
                passwdTV.setText("");
                passwdTV.requestFocus();
                break;
            case R.id.submit_btn:
                if (!NetworkHelper.networkStatusOK(getActivity())) {
                    ToastUtil.SnackerShow(getActivity(), getString(R.string.error_view_no_network));
                    return;
                }
                username = usernameTV.getText().toString().trim();
                passwd = passwdTV.getText().toString().trim();
                if (TextUtils.isEmpty(username)) {
                    ToastUtil.SnackerShow(getActivity(), getString(R.string.name_input_error));
                    return;
                }
                if (TextUtils.isEmpty(passwd) || passwd.length() < 6) {
                    ToastUtil.SnackerShow(getActivity(), getString(R.string.passwd_input_error));
                    return;
                }
                Logger.d(TAG, "userName " + username + "  passwd " + passwd + "  md5 " + MD5Helper.encodeMD5(passwd));
                login();
                break;
            case R.id.register_btn:
                break;
            case R.id.forget_passwd_btn:
                break;
            default:
                break;
        }
    }


    private void login() {
        dialog.show();
        okHttpClient = OKHttpUtil.getOkHttpClient(getActivity());
        RequestBody body = new FormEncodingBuilder().add("funName", "doLogin").add("userName", username).add("userPass", MD5Helper.encodeMD5(passwd)).add("phoneType", "1").build();
        Request request = new Request.Builder().url(APIUtils.BASE_URL).post(body).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            Handler handler = new Handler(getActivity().getMainLooper());

            @Override
            public void onFailure(Request request, IOException e) {

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        ToastUtil.SnackerShow(getActivity(), getString(R.string.login_error));
                    }
                });

            }

            @Override
            public void onResponse(Response response) throws IOException {
                // Logger.json(TAG, response.body().string());
                String body = response.body().string();
                Logger.json(TAG, body);
                try {
                    final JSONObject json = new JSONObject(body);
                    if (json.getString("recode").equals("2000")) {
                        Type type = new TypeToken<ApiResponse<UserInfo>>() {
                        }.getType();
                        ApiResponse<UserInfo> apiResponse = gson.fromJson(body, type);
                        Recontent<UserInfo> recontent = apiResponse.getRecontent();
                        List<UserInfo> list = recontent.getRelist();
                        UserInfo info = list.get(0);
                        Logger.d(TAG, "=========recode:" + "  userName:" + info.getUser_name() + "  key_word   " + info.getKey_word());
                        //editor.putString("key_word", info.getKey_word()).commit();
                        //editor.putString("user_id", info.getPk_kst_user_list()).commit();
                        Hawk.put(PreferencesKeyUtil.KEY_USER_NAME, username);
                        Hawk.put(PreferencesKeyUtil.KEY_PASSWD, passwd);
                        Hawk.put(PreferencesKeyUtil.KEY_KEY_WORD, info.getKey_word());
                        Hawk.put(PreferencesKeyUtil.KEY_USER_ID, info.getPk_kst_user_list());


                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (dialog.isShowing()) {
                                    dialog.dismiss();
                                }
                                Toast.makeText(getActivity(), getString(R.string.login_success), Toast.LENGTH_SHORT).show();

                                Intent intent = new Intent(getActivity(), MainActivity.class);
                                getActivity().startActivity(intent);

                            }
                        });
                    }else {
                        final String remsg = json.getString("remsg");
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (dialog.isShowing()) {
                                    dialog.dismiss();
                                }
                                ToastUtil.SnackerShow(getActivity(), remsg);
                                //Intent intent = new Intent(getActivity(), MainActivity.class);
                                //getActivity().startActivity(intent);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });
    }

}
